package co.fitstart.admin.web.controller.user;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.demo2do.core.support.Page;
import com.demo2do.core.support.Result;
import com.demo2do.core.utils.DateFormatUtils;
import com.demo2do.core.utils.DateUtils;
import com.demo2do.core.utils.JsonUtils;
import com.demo2do.core.web.resolver.Preloading;
import com.demo2do.core.web.utils.WebUtils;

import co.fitstart.admin.entity.content.VisitorRecordSearch;
import co.fitstart.admin.entity.security.Login;
import co.fitstart.admin.service.DataService;
import co.fitstart.admin.service.PrincipalService;
import co.fitstart.admin.service.SiteService;
import co.fitstart.admin.service.VisitorRecordService;
import co.fitstart.admin.web.interceptor.MenuSetting;
import co.fitstart.admin.web.resolver.Secure;
import co.fitstart.admin.web.view.ExcelTemplateView;
import co.fitstart.entity.principal.Principal;
import co.fitstart.entity.site.Site;
import co.fitstart.entity.user.VisitorRecord;

@Controller
@RequestMapping("/visitor-records")
@MenuSetting("menu-user")
public class VisitorRecordController {
    
    private static final Logger logger = LoggerFactory.getLogger(VisitorRecordController.class);
    
    @Autowired
    @Qualifier("dataService")
    private DataService<VisitorRecord> dataService;
    
    @Autowired
    private VisitorRecordService visitorRecordService;
    
    @Autowired
    private PrincipalService principalService;
    
    @Autowired
    private SiteService siteService;
    
    /**
     * 
     * @param login
     * @param day
     * @param page
     * @param request
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.GET)
    @MenuSetting("submenu-visitor-record-management")
    public ModelAndView list(@Secure Login login,
                             @RequestParam(value = "day", required = false) Integer day, 
                             Page page,
                             HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView("user/visitor-record/visitor-record-list");
        
        Site site = null;
        if (login.hasSite()){
          site = login.getSite();
        }
        
        Date date = null;
        if(day != null) {
            date = DateUtils.addDays(new Date(), day);
        } else {
            date = new Date();
        }
        modelAndView.addObject("date", date);
        modelAndView.addObject("isToday", new Date().equals(date));
        modelAndView.addObject("day", day == null ? 0 : day);
        
        List<VisitorRecord> visitorRecords = new ArrayList<>();
        if(login.isAreaManager() || login.isAreaServer()) {
            Principal principal = principalService.load(Principal.class, login.getId());
            
            List<Site> sites = siteService.listSite(principal);
            
            if(!sites.isEmpty()) {
                visitorRecords = visitorRecordService.list(sites, date, page);
            }
        } else {
            visitorRecords = visitorRecordService.list(site, date, page);
        }
        
        modelAndView.addObject("visitorRecords", visitorRecords);
        
        modelAndView.addObject("today", DateFormatUtils.format(new Date(), "yyyy-MM-dd"));
        
        modelAndView.addObject("page", page);
        
        modelAndView.addObject("queryString", WebUtils.extractQueryString(request, "page"));
        
        return modelAndView;
    }
    
    /**
     * @return
     */
    @RequestMapping(value = "/search", method=  RequestMethod.GET)
    public String search() {
        return "user/visitor-record/visitor-record-search";
    }
    
    /**
     * 
     * @param login
     * @param search
     * @param request
     * @param page
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.GET, params = "filter")
    @MenuSetting("submenu-visitor-record-management")
    public ModelAndView onSearch(@Secure Login login,
                                 VisitorRecordSearch search,
                                 HttpServletRequest request,
                                 Page page) {
        
        ModelAndView modelAndView = new ModelAndView("user/visitor-record/visitor-record-list");
        
        if (login.hasSite()) {
            search.setSite(login.getSite());
        } else if(login.isAreaManager() || login.isAreaServer()) {
            Principal principal = principalService.load(Principal.class, login.getId());
            
            search.setSites(siteService.listSite(principal));
        }
        
        List<VisitorRecord> visitorRecords = dataService.search(VisitorRecord.class, search, page);
        
        modelAndView.addObject("visitorRecords", visitorRecords);
        
        modelAndView.addObject("today", DateFormatUtils.format(new Date(), "yyyy-MM-dd"));
        
        modelAndView.addObject("refer", "search");
        modelAndView.addObject("queryString", WebUtils.extractQueryString(request, "page"));
        
        return modelAndView;
        
    }
    
    /**
     * 
     * @return
     */
    @RequestMapping(value = "/create", method = RequestMethod.GET)
    public ModelAndView create(){
        
        ModelAndView modelAndView = new ModelAndView("user/visitor-record/visitor-record-create");
        
        return modelAndView;
    }
    
    /**
     * 
     * @param visitorRecord
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.POST)
    public @ResponseBody String onCreate(@Secure Login login,
                                         VisitorRecord visitorRecord){
        
        Result result = new Result();
        
        try {
            Principal principal = principalService.load(Principal.class, login.getId());
            
            visitorRecordService.save(visitorRecord.initilize().editPrincipal(principal));
            
            result.success().message("添加访客记录成功！");
            
        } catch(Exception e) {
            logger.error("#onCreate - ", e);
            result.fail().message("添加访客记录失败！");
        }
        
        return JsonUtils.toJsonString(result);
    }
    
    /**
     * 
     * @param visitorRecordId
     * @return
     */
    @RequestMapping(value = "/{visitorRecordId}/edit", method = RequestMethod.GET)
    public ModelAndView edit(@PathVariable("visitorRecordId") Long visitorRecordId){
        
        ModelAndView modelAndView = new ModelAndView("user/visitor-record/visitor-record-edit");
        
        VisitorRecord visitorRecord = visitorRecordService.load(VisitorRecord.class, visitorRecordId);
        modelAndView.addObject("visitorRecord", visitorRecord);
        
        return modelAndView;
    }
    
    /**
     * 
     * @param visitorRecord
     * @return
     */
    @RequestMapping(value = "/{visitorRecordId}", method = RequestMethod.PATCH)
    public @ResponseBody String onEdit(@Secure Login login,
                                       @Preloading("id") VisitorRecord visitorRecord){
        
        Result result = new Result();
        
        try {
            Principal principal = principalService.load(Principal.class, login.getId());
            
            visitorRecordService.update(visitorRecord.editPrincipal(principal));
            
            result.success().message("修改访客记录成功！");
            
        } catch(Exception e) {
            logger.error("#onEdit - ", e);
            result.fail().message("修改访客记录失败！");
        }
        
        return JsonUtils.toJsonString(result);
    }
    
    /**
     * 
     * @param visitorRecordId
     * @return
     */
    @RequestMapping(value = "/{visitorRecordId}/delete", method = RequestMethod.GET)
    public ModelAndView delete(@PathVariable("visitorRecordId") Long visitorRecordId){
        
        ModelAndView modelAndView = new ModelAndView("user/visitor-record/visitor-record-delete");
        
        modelAndView.addObject("visitorRecordId", visitorRecordId);
        
        return modelAndView;
    }
    
    /**
     * 
     * @param visitorRecord
     * @return
     */
    @RequestMapping(value = "/{visitorRecordId}", method = RequestMethod.DELETE)
    public @ResponseBody String onDelete(@Preloading("id") VisitorRecord visitorRecord){
        
        Result result = new Result();
        
        try {
            
            visitorRecordService.update(visitorRecord.disable());
            
            result.success().message("删除访客记录成功！");
            
        } catch(Exception e) {
            
            logger.error("#onDelete - ", e);
            
            result.fail().message("删除访客记录失败！");
            
        }
        
        return JsonUtils.toJsonString(result);
    }

    /**
     * 
     * @return
     */
    @RequestMapping(value = "/export-view", method = RequestMethod.GET)
    public ModelAndView export(){
        
        ModelAndView modelAndView = new ModelAndView("user/visitor-record/visitor-record-export");
        
        return modelAndView;
    }
    
    /**
     * 
     * @param login
     * @param siteId
     * @param receiverId
     * @param search
     * @return
     */
    @RequestMapping(value = "/export", method = RequestMethod.GET)
    public ModelAndView onExport(@Secure Login login,
                                 @RequestParam(value = "siteId", required = false) Long siteId,
                                 @RequestParam(value = "receiverId", required = false) Long receiverId,
                                 VisitorRecordSearch search){
        ModelAndView modelAndView = new ModelAndView(new ExcelTemplateView("visitor-record-report.xls"));
        
        Site site = null;
        if(login.hasSite()) {
            site = login.getSite();
        } else if(siteId != null) {
            site = siteService.load(siteId);
        }
        
        if(site == null) {
            if(login.isAreaManager() || login.isAreaServer()) {
                Principal principal = principalService.load(Principal.class, login.getId());
                search.setSites(siteService.listSite(principal));
            }
        } else {
            search.setSite(site);
        }
        
        Principal receiver = null;
        if(receiverId != null) {
            receiver = principalService.load(Principal.class, receiverId);
        }
        search.setReceiver(receiver);
        
        List<VisitorRecord> visitorRecords = visitorRecordService.search(search);
        
        modelAndView.addObject("visitorRecords", visitorRecords);
        modelAndView.addObject("site", site);
        modelAndView.addObject("receiver", receiver);
        modelAndView.addObject("begin", DateFormatUtils.format(search.getBegin(), "yyyy-MM-dd"));
        modelAndView.addObject("end", DateFormatUtils.format(search.getEnd(), "yyyy-MM-dd"));
        
        return modelAndView;
    }
}
